import Foundation
import Flutter



public class SwiftAliVodVideoPlugin: NSObject, FlutterPlugin {
    static var flutterChannel:FlutterMethodChannel?
    
    fileprivate var upVideoManagers: [String:VGUpVideoManager] = [:]
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        flutterChannel = FlutterMethodChannel(name: "ali_vod_video", binaryMessenger: registrar.messenger())
        let instance = SwiftAliVodVideoPlugin()
        registrar.addMethodCallDelegate(instance, channel: flutterChannel!)
        
        
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        
        switch call.method {
            case "uploadVideo":
                //MARK: uploadVideo 上传
                let argument :Any? = call.arguments
                if(argument == nil){
                    return result("参数不能为空");
                }
                let params :[String:Any] = argument as! [String:Any]
                let id:String? = params["id"] as? String
                let filePath:String? = params["filePath"] as? String
                let cateId:String? = params["cateId"] as? String
                
                let tempGroupId:String? = params["templateGroupId"] as? String
                let definition:String? = params["definition"] as? String
                let userData:String? = params["UserData"] as? String
                
                let needProgress:Bool = params["needProgress"] as? Bool ?? false
                let dateFormatte = DateFormatter()
                dateFormatte.dateFormat = "yyyyMMddHHmmss"
                
                let fileName =  dateFormatte.string(from: Date()) + "_"+String( 1000 + Int(arc4random_uniform(999)))+".mp4"
                if let filePath = filePath,let id = id,let cateId = cateId{
                    let upVideoManager = VGUpVideoManager()
                    upVideoManagers[id] = upVideoManager
                    upVideoManager.upload(id:id,cateId: cateId, path: filePath,templateGroupId: tempGroupId ?? "8cae871c81c42affda3dd93b8533e729", definition: definition ?? "SD", userData: userData ?? "", fileName: fileName, progressClosure: {
                        (progress) in
                        print("上传进度\(progress)")
                        if needProgress{
                            if let channel = SwiftAliVodVideoPlugin.flutterChannel{
                                let params = ["filePath":filePath,"id":id,"progress":Double(progress.completedUnitCount * 100 / progress.totalUnitCount)]
                                channel.invokeMethod("onUploadProgressChange", arguments: params)
                            }
                        }
                    } , completionClosure: {dict in
                        if self.upVideoManagers.keys.contains(id){
                            self.upVideoManagers.removeValue(forKey: id)
                            result(dict)
                        }
                    }, faliedClosure:{
                        (msg) in
                        result(["url":""])
                    })
                }
                break;
            case "cancelUploadVideo":
                //MARK: cancelUploadVideo取消上传
                let argument :Any? = call.arguments
                if(argument == nil){
                    return result("参数不能为空");
                }
                let params :[String:Any] = argument as! [String:Any]
                let id:String? = params["id"] as? String
                if let id = id{
                    upVideoManagers[id]?.cancelAll()
                    upVideoManagers.removeValue(forKey: id)
                }
                if let channel = SwiftAliVodVideoPlugin.flutterChannel{
                    channel.invokeMethod("onUploadCancel", arguments: argument)
                }
                break
            case "cancelUploadVideoAll":
                
                //MARK: cancelUploadVideoAll 全部取消上传
                upVideoManagers.forEach {
                    $0.value.cancelAll()
                }
                upVideoManagers.removeAll()
                
                if let channel = SwiftAliVodVideoPlugin.flutterChannel{
                    channel.invokeMethod("onUploadCancel", arguments: nil)
                }
                result(.none)
                break
            default :
                result("iOS " + UIDevice.current.systemVersion)
                break
        }
        
    }
}

